<?php

/*
 * The default response format is string (used by the web page renderer).
 * JSON response format can be requested by appending the 'format=json' parameter to the query string.
 * In case of any error, depending on the requested response format, returns:
 * - JSON format: error JSON string
 * - default (string) format: string "NULL"
 *
 * ERRORS:
 * - ERROR_MISSING_ARGUMENT - in case of any missing mandatory arguments (lon or lat)
 * - ERROR_GEOLOCATION_SERVER_UNAVAILABLE - if can't make connection to the geolocation server
 * - ERROR_GEOLOCATION_REQUEST_FAIL - if the geolocation in its response returns non-success (200) status code
 */

header('Cache-Control: private, no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
header('Pragma: no-cache');

include_once './Location.php';
include_once './Error.php';
include_once './log4php/Logger.php';
include_once './Utils.php';
include_once './constants.php';
include_once './Situare.php';

// response
define('RESPONSE_TXT_ERROR', 'NULL');
define('RESPONSE_JSON_LON', 'lon');
define('RESPONSE_JSON_LAT', 'lat');
define('RESPONSE_JSON_ADDRESS', 'address');

Logger::configure('./log4j.properties');

$log = Logger::getLogger(basename(__FILE__));
$log->debug("[START] " . basename(__FILE__));

try {
    $inputArray = Utils::getInputParameters();
    $format = Utils::getInputParameterValue($inputArray, PARAM_FORMAT, FORMAT_TEXT);
    $api = Utils::getInputParameterValue($inputArray, PARAM_API, NULL);
    $lon = Utils::getLongitude($inputArray);
    $lat = Utils::getLatitude($inputArray);
    $locationStr = Location::getLocationAddress($lon, $lat);
    $log->debug("address = '" . $locationStr . "'");

    $responseArray = array();
    $responseArray[RESPONSE_JSON_LON] = $lon;
    $responseArray[RESPONSE_JSON_LAT] = $lat;
    $responseArray[RESPONSE_JSON_ADDRESS] = $locationStr;

    if ($api == API_2_0) {
        echo Situare::getApi20Response($responseArray);
    }
    else if ($format == FORMAT_JSON) {              // format JSON string
        echo json_encode($responseArray);
    }
    else {                                          // format text
        echo $locationStr;
    }
}
catch (Exception $e) {
    $log->error("Exception:");
    $log->error("Code: " . $e->getCode());
    $log->error("Message: " . $e->getMessage());
    $log->error("Location: " . $e->getFile() . " at line " . $e->getLine());
    $log->error("Trace: " . $e->getTraceAsString());

    if ($api == API_2_0) {
        echo Situare::getApi20Response($e);
    }
    else if ($format == FORMAT_JSON) {
        echo getExceptionAsJson($e);
    }
    else {
        echo RESPONSE_TXT_ERROR;
    }
}

$log->debug("[ END ] " . basename(__FILE__));
?>
